<?php

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use DfaFilter\SensitiveHelper;

/**
 *  敏感词
 */
class BlackWords extends Model
{
    protected $table = 'black_words';
    protected $fillable = ['word', 'word_type', 'flag'];

    //色情
    const TYPE_SEX = 1;
    //政治
    const TYPE_POL = 2;
    //暴力
    const TYPE_VIL = 3;
    //广告
    const TYPE_AD = 4;

    static $handle = null;

    /**
     * 获取处理对象
     */
    static function getHandle()
    {
        if (self::$handle) return self::$handle;
        $badWords = self::where('flag', 1)->pluck('word')->toArray();
        return self::$handle = SensitiveHelper::init()->setTree($badWords);
    }

    /**
     * 获取敏感词组
     */
    static function checkLegal($content = '', $msgId = '')
    {
        if (!$content) return ['result' => 1, 'words' => []];
        //qq号匹配,手机号
        $modes = [
            'qq' => '/[1-9][0-9]{4,}/',
            'phone' => '/\d{3}-\d{8}|\d{4}-\d{7}|\d{11}/',
        ];
        foreach ($modes as $key => $mode) {
            if (preg_match($mode, $content)) {
                log_info(__METHOD__ . "==MsgId:{$msgId}==Content:{$content}==CheckMode:{$key}");
                return ['result' => 0, 'words' => []];
            }
        }
        $handle = self::getHandle();
        $wordGroup = $handle->getBadWord($content);
        if (!$legal = empty($wordGroup)) {
            log_info(__METHOD__ . "==MsgId:{$msgId}==Content:{$content}==Words:" . json_encode($wordGroup));
        }
        return ['result' => $legal, 'words' => $wordGroup];
    }

    static function addWords($words = [])
    {
        foreach ($words as $word) {
            $ret = self::updateOrCreate(['word' => $word], [
                'word' => $word,
                'word_type' => 1
            ]);
            dump("{$word}");
        }
    }
}
